package main

import (
	"database/sql"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	_ "github.com/mattn/go-sqlite3"
	"log"
	"time"
)

func main() {
	sqlitedb, err := sql.Open("sqlite3", "temp_humi.db")
	sql_table := `CREATE TABLE IF NOT EXISTS "temp_humi" (
	  "id" INTEGER PRIMARY KEY AUTOINCREMENT,
	  "temp" VARCHAR(100) NULL,
	  "humi" VARCHAR(100) NULL,
	  "created" TIMESTAMP default (datetime('now', 'localtime'))
	);`
	_, err = sqlitedb.Exec(sql_table)
	if err != nil {
		log.Println("sqlite:", err)
	}

	r := gin.Default()
	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"PUT", "PATCH", "GET", "POST", "OPTIONS", "DELETE"},
		AllowHeaders:     []string{"*"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	}))
	r.POST("/ping", func(c *gin.Context) {
		json := make(map[string]interface{}) //注意该结构接受的内容
		c.BindJSON(&json)
		stmt, err := sqlitedb.Prepare("INSERT INTO temp_humi(temp, humi)  values(?, ?)")
		res, err := stmt.Exec(json["temp"], json["humi"])
		id, err := res.LastInsertId() //返回新增的id号
		if err != nil {
			log.Println(err)
		}
		log.Println(id)
		log.Printf("%v", &json)
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.GET("/gettemp_humi", func(c *gin.Context) {
		deleteOldData(sqlitedb)
		var id, temp, humi, created string
		err := sqlitedb.QueryRow("select * from temp_humi ORDER BY id DESC LIMIT 1").Scan(&id, &temp, &humi, &created)
		if err != nil {
			log.Println(err)
		}
		c.JSON(200, gin.H{
			"temp": temp,
			"humi": humi,
		})
	})

	r.Run(":8001")
}

func deleteOldData(db *sql.DB) {
	// 删除指定天数之前的数据,这里是删除昨天之前的数据
	stmt := "DELETE FROM temp_humi WHERE created < datetime('now', '-1 day')"

	_, err := db.Exec(stmt)
	if err != nil {
		log.Println(err)
	}
}
